﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sispe.Entities;
using System.Data;

namespace Sispe.Repository
{
    public class EstudioRepository:MasterRepository, IEstudioRepository
    {
        public List<ESTUDIO> GetAllFromEstudios()
        {
            var query = from s in context.ESTUDIOS.Include("GRADO")
                        select s;
            return query.ToList();
        }

        public List<ESTUDIO> GetAllFromEstudiosByDescripcion(string descripcion)
        {
            var query = from s in context.ESTUDIOS.Include("GRADO")
                        select s;
            if (descripcion != null && descripcion != string.Empty && descripcion != "")
            {
                query = from s in context.ESTUDIOS
                        where s.Descripcion.Contains(descripcion) ||
                                  s.Codigo.ToUpper().Contains(descripcion)
                        select s;
            }
            return query.ToList();
        }

        public ESTUDIO GetFromEstudioById(int id)
        {
            var query = from s in context.ESTUDIOS.Include("GRADO")
                        where s.IdEstudios.Equals(id)
                        select s;
            return query.SingleOrDefault();
        }

       

        public void AddEstudios(ESTUDIO estudios)
        {
            context.Entry(estudios.GRADO).State = EntityState.Unchanged;
            context.ESTUDIOS.Add(estudios);
            context.SaveChanges();
        }

        public void UpdateEstudios(ESTUDIO estudios)
        {
            context.ESTUDIOS.Attach(estudios);
            context.Entry(estudios).State = System.Data.EntityState.Modified;
            context.SaveChanges();
        }

        public void RemoveEstudios(int id)
        {
            var existe = context.ESTUDIOS.Find(id);

            if (existe != null)
            {
                context.ESTUDIOS.Remove(existe);
                context.SaveChanges();
            }
        }


        public bool ExisteDuplicidad(string descripcion, string codigo, int id)
        {
            var query = from s in context.ESTUDIOS
                        where (s.Descripcion.CompareTo(descripcion) == 0 &&
                                  s.Codigo.ToUpper().CompareTo(codigo.ToUpper()) == 0)
                                  && s.IdEstudios !=id
                        select s;
            return query.Any();
        }


        public bool GetFromEstudioByGradoById(int idGrado)
        {
            var query = from e in context.ESTUDIOS.Include("GRADO")
                        where e.IdGrado.Equals(idGrado)
                        select e;
            return query.Any();
        }
    }
}
